package cn.lds.j375.healthexam.controller;

import cn.lds.j375.healthexam.entity.User;
import cn.lds.j375.healthexam.dto.ResultDTO;
import cn.lds.j375.healthexam.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.text.ParseException;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/do_login")
    public String doLogin(User user, HttpSession session, Model model){
        ResultDTO<User> userResultDTO = userService.loginUser(user);

        if (userResultDTO.getCode().equals(4000)){
            model.addAttribute("err",userResultDTO.getInfo());
            return "/login";
        }

        session.setAttribute("loginUser",userResultDTO.getObj());

        return "redirect:/";
    }

    @GetMapping("logout")
    public String loginOut(HttpSession session){
        session.removeAttribute("loginUser");
        return "redirect:/";
    }

    @GetMapping("/reg")
    public String reg(){
        return "reg";
    }

    @PostMapping("do_reg")
    public String doReg(User user) throws ParseException {

        userService.regUser(user);


        return "login";
    }
}
